<!--
 * @Description: 告警类别管理
-->
<template>
  <BaseMainSlot>
    <template v-slot:searchbox>
      <div class="seach-box">
        <div class="select-box-content">
          <div class="select-box-content-name">类别名称：</div>
          <el-input
            v-model="alarmTypeName"
            clearable
            placeholder="请输入类别名称"
            @change="search()"
          />
        </div>
      </div>
    </template>
    <template v-slot:btnsBar>
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :page-no="187"
        @add="add"
        @del="delmessage"
      />
    </template>
    <template v-slot:content>
      <e-table
        rowKey="alarmTypeId"
        :table-data="tableData"
        :table-columns="tableLabel"
        :tableOption="tableOption"
        :page="currentPage"
        :size="pageSize"
        :total="totalSize"
        :loading="loading"
        @sizeChange="changePageSize"
        @pageChange="changeCurrentPage"
        @tableUpdatePlus="mixTableUpdatePlus"
        @handleSelectionChange="handleSelectionChange"
      >
      <template slot="alarmType"
      slot-scope="scoped"

      v-if="scoped.row.alarmTypeId">
        <span
              class="table-btns-box"
              @click="seeInfo(scoped.row)"
            >
              <i class="el-icon-view"></i>
              <span>查看详情</span>
            </span>
      </template>
        <template
          slot="operate"
          slot-scope="scoped"
          v-if="scoped.row.alarmTypeId"
        >
          <span class="table-btns-box" @click="handleEdit(scoped.row)">
            <i class="el-icon-edit-outline"></i>
            <span>修改</span>
          </span>

          <span
            class="table-btns-box table_del_btn"
            @click="handleDelete(scoped.row.alarmTypeId)"
          >
            <i class="el-icon-delete"></i>
            <span>删除</span>
          </span>
        </template>
      </e-table>
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '告警类别信息'"
        :visible.sync="showAddEditDialog"
        :before-close="cancel"
        width="40%"
      >
        <!-- :show-message="canInput" -->
        <el-form
          ref="formData"
          label-position="left"
          :rules="rules"
          :model="formData"
          class="el-form"
        >
          <el-form-item label="告警类别名称:" class="w50p" prop="alarmTypeName">
            <el-input v-model="formData.alarmTypeName" clearable />
          </el-form-item>
          <el-form-item label="告警类别描述:" class="w50p" prop="describe">
            <el-input v-model="formData.describe" clearable />
          </el-form-item>
          <el-form-item
            v-if="nowChanceStau === 'add' || nowChanceStau === 'edit'"
            label="数据类型选择"
            class="w50p"
            prop="nowdataType"
          >
            <el-select
              v-model="nowdataType"
              clearable
              multiple
              @change="addDataType"
            >
              <el-option
                v-for="(item, index) in dataTypeList"
                :key="item.dataTypeId"
                :value="item.dataTypeId"
                :label="item.dataTypeName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所关联数据类型:" class="w100p">
            <div class="contact-view">
              <div
                v-for="(item, index) in showdatatypeList"
                :key="index"
                class="contact-view-but"
                @click="delDataType(index)"
              >
                {{ item.dataTypeName }}
                <i
                  v-if="nowChanceStau === 'add' || nowChanceStau === 'edit'"
                  class="el-icon-close"
                ></i>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>

      <ShowDialog
        :showInfo="seeInfoDialog"
        :seeInfoObject="editObject"
        :titleText="titleText"
        @closeDialog="() => { seeInfoDialog = false;editObject= {}; queryPageList() }"
      />
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import nowpagereq from "@/api/monitoring-alarm/alarm-category-management";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import ShowDialog from "./components/show-dialog.vue";

import { mymixin } from "@/utils/mixin";
import { mapGetters } from "vuex";
export default {
  name: "AlarmCategoryManagement",
  components: { ActionBar, BaseMainSlot, ShowDialog },
  mixins: [mymixin],
  data() {
    var validatePass = (rule, value, callback) => {
      if (this.nowdataType === null || this.nowdataType.length === 0) {
        callback(new Error("请输入选择数据类型"));
      } else {
        callback();
      }
    };
    return {
      // 搜索内容
      alarmTypeName: "",
      tableLabel: [
        {
          param: "alarmTypeName",
          label: "告警类别名称",
          show: true,
          notSearch: true,
        },
        {
          param: "alarmTypeName",
          label: "关联数据类型",
          slotName: "alarmType",
          show: true,
          notSearch: true,
        },

        {
          param: "describe",
          label: "告警类别描述",
          show: true,
          notSearch: true,
        },
      ],
      // 表单事件
      tableOption: {
        label: "操作",
        options: [
          {
            label: "操作",
            slotName: "operate",
          },
        ],
      },
      rules: {
        alarmTypeName: [
          { required: true, message: "请输入告警类别名称", trigger: "blur" },
        ],
        describe: [
          { required: true, message: "请输入告警类别描述", trigger: "blur" },
        ],
        nowdataType: [
          { required: true, validator: validatePass, trigger: "change" },
        ],
      },
      // 当前数据类型选择的index
      nowdataType: [],
      // 数据类型列表
      dataTypeList: [],
      // 展示的数据类型列表
      showdatatypeList: [],

      // 选中的数据项数组 alarmTypeId组成 (此数组最多为一个)
      selectIdList: [],
      dialogTitle: "",
      seeInfoDialog: false,
      editObject: {},
titleText: '',
      showAddEditDialog: false,
      formData: {
        alarmTypeName: "",
        describe: "",
      },
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  created() {
    // 获取表格数据
    this.queryPageList();
    this.getselectlist();
  },
  mounted() {},
  methods: {
    changeTableSort(column) {
      this.sortList = column.order
        ? [
            {
              property: column.prop,
              direction: column.order == "ascending" ? "asc" : "desc",
            },
          ]
        : [];
      this.queryPageList();
    },

    seeInfo(row) {
      this.titleText = "关联数据类型详情";
      this.editObject = JSON.parse(JSON.stringify(row));
      console.log(this.editObject);
      this.seeInfoDialog = true;
    },
    // 添加一条数据类别
    addDataType(e) {
      this.showdatatypeList = [];
      if (this.nowChanceStau === "add" || this.nowChanceStau === "edit") {
        e.forEach((item) => {
          this.dataTypeList.forEach((el) => {
            if (el.dataTypeId === item) {
              let addData = {
                dataTypeId: el.dataTypeId,
                dataTypeName: el.dataTypeName,
              };
              this.showdatatypeList.push(addData);
            }
          });
        });
      }
    },
    // 删除一条数据
    delDataType(index) {
      if (this.nowChanceStau === "add" || this.nowChanceStau === "edit") {
        this.showdatatypeList.splice(index, 1);
        this.nowdataType.splice(index, 1);
      }
    },
    // 获取下拉数据
    getselectlist() {
      // 获取所有数据类型
      nowpagereq.getalldatalist().then((res) => {
        this.dataTypeList = res.data;
      });
    },
    queryPageList() {
      this.loading = true;
      this.showdatatypeList = [];
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
      };
      if (this.alarmTypeName) {
        let searchparams = {
          alarmTypeName: this.alarmTypeName,
        };
        nowpagereq.querybycondition(searchparams).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            // this.$message.success('查询成功')
          } else {
            this.$message.error("查询失败");
          }
          let data = res.data;
          // 赋值总条数
          this.totalSize = data.length;
          // 赋值数组
          this.tableData = data;
          this.addblankmet();
          this.resetActionBar();
        });
      } else {
        nowpagereq.getlist(params).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            this.$message.error("查询失败");
          }
          let data = res.data;
          // 赋值总条数
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        });
      }
    },
    search() {
      this.currentPage = 1;
      this.queryPageList();
    },

    // 添加
    add() {
      this.addActive = false;
      this.openDialog("add");
      this.formData = {};
    },
    // 取消
    cancel() {
      this.addActive = true;
      this.closeDialog();
      this.formData = {};
    },
    handleEdit(row) {
      this.nowdataType = [];
      // console.log(this.dataTypeList, "whw");
      console.log(row);
      if (row.alarmTypeId) {
        this.formData = { ...row };
        row.alarmTypeDataTypeMapperList.forEach((el) => {
          this.nowdataType.push(el.dataTypeId);
        });
        this.showdatatypeList = row.alarmTypeDataTypeMapperList;
        this.openDialog("edit");
      }
    },
    handleSelectionChange(list) {
      this.selectIdList = [];
      let notvalue = true;
      this.selectIdList = list.map((item) => {
        if (item.alarmTypeId) {
          return item.alarmTypeId;
        } else {
          notvalue = false;
          return "";
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        return;
      }
      if (this.selectIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      nowpagereq.dellist(this.selectIdList).then((res) => {
        if (res.code === 1) {
          this.$message.success("删除成功");
          this.queryPageList();
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    handleDelete(data) {
      // nowpagereq.del(data).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success("删除成功");
      //     this.queryPageList();
      //   } else {
      //     this.$message.error("删除失败");
      //   }
      // });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          nowpagereq.del(data).then((res) => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.queryPageList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    save() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            let addparams = {
              ...this.formData,
            };
            addparams["alarmTypeDataTypeMapperList"] = [];
            this.nowdataType.forEach((el) => {
              this.dataTypeList.forEach((item) => {
                if (item.dataTypeId === el) {
                  let obj = {
                    dataTypeId: item.dataTypeId,
                    dataTypeName: item.dataTypeName,
                  };
                  addparams["alarmTypeDataTypeMapperList"].push(obj);
                }
              });
            });
            nowpagereq.editlist(addparams).then((res) => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.closeDialog();
                this.queryPageList();
              } else {
                this.$message.error("修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let addparams = {
              ...this.formData,
            };
            addparams["alarmTypeDataTypeMapperList"] = [];
            this.nowdataType.forEach((el) => {
              this.dataTypeList.forEach((item) => {
                if (item.dataTypeId === el) {
                  let obj = {
                    dataTypeId: item.dataTypeId,
                    dataTypeName: item.dataTypeName,
                  };
                  addparams["alarmTypeDataTypeMapperList"].push(obj);
                }
              });
            });
            // console.log(addparams); return
            nowpagereq.addlist(addparams).then((res) => {
              if (res.code === 1) {
                this.$message.success("新增成功！");
                this.closeDialog();
                this.queryPageList();
              } else {
                this.$message.error("新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    openDialog(type) {
      this.showAddEditDialog = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.nowdataType = [];
      this.showdatatypeList = [];
      this.$nextTick(() => {
        this.$refs.formData.resetFields();
      });
      this.showAddEditDialog = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    },
  },
};
</script>

<style scoped lang="scss">
.contact-view {
  width: 100%;
  // border: #6ecae3 1px solid;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .contact-view-but {
    background-color: #409eff;
    border: 1px solid #409eff;
    color: #fff;
    width: 200px;
    height: 36px;
    line-height: 36px;
    font-size: 18px;
    margin: 5px;
    text-align: center;
    .el-icon-close {
      height: 36px;
      line-height: 36px;
      float: right;
      padding-right: 6px;
    }
  }
}
</style>
